var SHARE={
    marquerrMove:function(){
        var a = $("#msgBox");
        var b = function() {
            var b = -1 * parseInt(a.find("li").eq(0).height());
            a.find("ul").animate({
                "margin-top": b + "px"
            }, function() {
                a.find("ul li:eq(0)").appendTo(a.find("ul")), a.find("ul").css({
                    "margin-top": 0
                })
            })
        };
        setInterval(b, 3000)
    },
    popup:function(ex){
    	ex ? $('.mask').show().next().show() : $('.mask').hide().next().hide();
    },
    //获取页面url参数；
    GetQueryString: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
        var r = window.location.search.substr(1).match(reg);
        if (r!=null) return (r[2]); return null;
    },
    isWeiXin: function() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    },
    downLoad: function(){
        window.location.href="http://a.app.qq.com/o/simple.jsp?pkgname=com.ppdai.huanapp";
    }
};
//获取渠道参数；
var mobile;
var isWx = SHARE.isWeiXin(),
    isiOS = navigator.userAgent.match('iPad')
                     || navigator.userAgent.match('iPhone')
                     || navigator.userAgent.match('iPod'),
    dlurl =  SHARE.GetQueryString("url"),
    iosURL     = !dlurl ? "https://itunes.apple.com/cn/app/jie-zou-da-shi/id1176078944?mt=8" : dlurl,
    isAndroid  = navigator.userAgent.match('Android');
var uId =  SHARE.GetQueryString("shareId");
    uId = !uId ? 0 : uId;
var _src= SHARE.GetQueryString("source");
    _src= !_src ? "":_src;
//点击传值并下载；
$('#getBtn').on('click',function(){
    mobile = $.trim($('#phoneNum').val());
    if(mobile.length<1){
        $('#phoneNum').attr('placeholder','请先输入手机号~').addClass('redPlhd');
        return;
    }else if(!/^(13|14|15|17|18)[0-9]{9}$/.test(mobile)){
        $('#phoneNum').val('').attr('placeholder','请输入正确的手机号~').addClass('redPlhd');
        return;
    }
    $.ajax({
            type :'get',
            async: false,
            dataType:'json',
            url  : "//m.ppdai.com/Activity/InviteNewUser",
            data : {mobile:mobile,shareId:uId},
            success: function(data){
                if(data.Result==0){
                    if(data.Content.IsNewUser){
                        window.location.href="register.html?phoneNum="+mobile+"&shareId="+uId+"&source="+_src;
                    }else{
                        SHARE.popup(true);
                    }
                }else{
				     alert(data.ResultMessage);
				}
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                alert("网络错误,请稍后重试~")
            }
    })
})
$('#dwload').on('click',function(){
    SHARE.popup(false);
    SHARE.downLoad();
})

// shareID
var inviteShareId = 0;
// 注册获取shareID方法
var getInviteShareId = function (cb) {
	var url = '/huanhuan/ActivityService/UserActivityShare';
	var param = {};
	var callback = function getShareIdCallback(data) {
		data = JSON.parse(data);
		if (data.Result !== 0) {
			alert('邀请失败，请稍后再试');
		}
		inviteShareId = data.Content.ShareId;
		cb();
	};
	try {
		WebViewJavascriptBridge.callHandler('goRequestData', {
			'code': 1,
			'name': '邀请好友请求ShareID',
			'data': {
				'url': url,
				'param': param,
				'callback': callback
			}
		}, callback);
	} catch(ex) {
		window.getShareIdCallback = callback;
		try {
			AppBridge.goRequestData(url, param, window.getShareIdCallback.name);
		} catch (ex) {
			console.log('邀请失败，请刷新后再试');
		}
	}
};
// 显示Loading
var showLoading = function () {
	try {
		WebViewJavascriptBridge.callHandler('showLoading', {
			'code': 1,
			'name': '显示原生Loading',
			'data': {}
		});
	} catch(ex) {
		try {
			AppBridge.showLoading();
		} catch(ex) {
			console.log('请在APP中打开');
		}
	}
};
// 隐藏Loading
var dismissLoading = function () {
	try {
		WebViewJavascriptBridge.callHandler('dismissLoading', {
			'code': 1,
			'name': '隐藏原生Loading',
			'data': {}
		});
	} catch(ex) {
		try {
			AppBridge.dismissLoading();
		} catch(ex) {
			console.log('请在APP中打开');
		}
	}
};
// 跳转登录
var goLogin = function (url, title) {
	try {
		WebViewJavascriptBridge.callHandler('goLogin', {
			'code': 1,
			'name': '调用登录界面',
			'data': {
				'url': url,
				'title': title
			}
		});
	} catch(ex) {
		try {
			AppBridge.goLogin(url, title);
		} catch (ex) {
			alert('goLogin failed');
			throw ex;
		}
	}
};
$('#invite_btn').on('click', function () {
	var cb = function () {
		dismissLoading();
		/*if (inviteShareId === 0) {
		 console.log('邀请失败，请刷新后再试');
		 return;
		 }*/
		var shareData = {
			'logoUrl': 'https://hh.ppdaicdn.com/static/images/home/logo.jpg',
			'title': '送您5万额度还信用卡，1秒到账，再送10元红包！',
			'subTitle': '拍拍贷旗下信用卡代还APP，利息只有银行的3折，500万信用卡用户都在用。',
			'shareUrl': 'http://m.ppdai.com/act/super_huan/invite.html?shareid=' + inviteShareId + '&version=1',
			'redbag': 1
		};
		try {
			WebViewJavascriptBridge.callHandler('callupShare', {
				'code': 1,
				'name': '邀请好友分享',
				'data': shareData
			});
		} catch(ex) {
			try {
				AppBridge.callupShare(JSON.stringify(shareData));
			} catch (ex) {
				console.log('邀请失败，请刷新后再试');
			}
		}
	};
	showLoading();
	// try get user infomation
	try {
		WebViewJavascriptBridge.callHandler('getUserInformation', {
			'code': 1,
			'name': '获取用户信息',
			'data': {}
		}, function (res) {
			res = JSON.parse(res);
			dismissLoading();
			if (res.Result !== '0' || !res.Content.UserID) {
				WebViewJavascriptBridge.callHandler('goLogin', {
					'code': 1,
					'name': '调用登录界面',
					'data': {
						'url': location.href,
						'title': document.title
					}
				});
				return;
			}
			getInviteShareId(cb);
		});
	} catch(ex) {
		try {
			var res = AppBridge.getUserInformation();
			res = JSON.parse(res);
			dismissLoading();
			if (res.Result !== '0' || !res.Content.UserID) {
				AppBridge.goLogin(location.href, document.title);
				return;
			}
			getInviteShareId(cb);
		} catch (ex) {
			console.log('获取用户登录失败，请刷新后再试');
		}
	}
});
var evt = new Event('WebViewJavascriptBridgeReady');
// WebViewJavascriptBridgeReady
document.addEventListener('WebViewJavascriptBridgeReady', function () {
	//getInviteShareId();
}, false);
// 注册WebViewJavascriptBridge
var injectWebViewJavascriptBridge = function (callback) {
    if (window.WebViewJavascriptBridge) {
        return callback();
    }
    // ios
    if (window.WVJBCallbacks) {
        return window.WVJBCallbacks.push(callback);
    }
	window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    WVJBIframe.style.display = 'none';
    document.body.appendChild(WVJBIframe);
    setTimeout(function () {
        document.body.removeChild(WVJBIframe);
        // ios appbridge
        if (!window.WebViewJavascriptBridge) {
	        callback();
        }
    }, 0);
};
// 注册WebViewJavascriptBridge回调
var injectWebViewJavascriptBridgeCallback = function () {
	document.dispatchEvent(evt);
};
// init
if (isiOS) {
	injectWebViewJavascriptBridge(injectWebViewJavascriptBridgeCallback);
}
